﻿using System;
using System.Collections.Generic;
using System.Linq;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Services;
using Microsoft.SharePoint;
using Eneta.Portal.Common.Definitions;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Publishing;
using Constants;

namespace Eneta.Portal.Common.Repository
{
    public class LiteratureRepository : BaseRepository
    {
        public LiteratureRepository(SPWeb web)
            : base(web)
        {

        }
        public List<LiteratureDto> GetLiteratureItems(string webUrl, SPContentTypeId contentTypeId)
        {
            List<LiteratureDto> books = new List<LiteratureDto>();

            var sec = new SPSecurity.CodeToRunElevated(delegate
            {
                using (SPSite site = new SPSite(SiteId))
                using (SPWeb studyWeb = site.OpenWeb(webUrl))//webId))
                {
                    Logger.LogInfo("LiteratureRepository: " + studyWeb.Title);
                    var list = studyWeb.Lists[PublishingWeb.GetPagesListId(studyWeb)];//studyWeb.GetList(listUrl);
                    
                    var items = base.GetApprovedItems(list, contentTypeId, "Created", false);
                    Logger.LogInfo("LiteratureRepository: kinnitatud elemente: " + items.Count);
                    books = ToLiteratureItems(studyWeb, items);
                }
            });
            SPSecurity.RunWithElevatedPrivileges(sec);
            return books;
        }

        public List<LiteratureDto> GetPendingLiteratureItems(string webUrl, SPContentTypeId contentTypeId)
        {
            List<LiteratureDto> literatureItems = new List<LiteratureDto>();

            var sec = new SPSecurity.CodeToRunElevated(delegate
            {
                using (SPSite site = new SPSite(SiteId))
                using (SPWeb studyWeb = site.OpenWeb(webUrl))
                {
                    var list = studyWeb.Lists[PublishingWeb.GetPagesListId(studyWeb)];

                    var items = base.GetPendingItems(list, contentTypeId, "Created", true);
                    literatureItems = ToLiteratureItems(studyWeb, items);
                }
            });
            SPSecurity.RunWithElevatedPrivileges(sec);
            return literatureItems;
        }

        public List<LiteratureDto> GetUserLiteratureItems(string webUrl, string contentType, int userId)
        {
            List<LiteratureDto> literatureItems = new List<LiteratureDto>();

            var sec = new SPSecurity.CodeToRunElevated(delegate
            {
                using (SPSite site = new SPSite(SiteId))
                using (SPWeb studyWeb = site.OpenWeb(webUrl))
                {
                    literatureItems = GetUserLiteratureItems(studyWeb, contentType, userId);
                }
            });
            SPSecurity.RunWithElevatedPrivileges(sec);
            return literatureItems;
        }

        public List<LiteratureDto> GetUserLiteratureItems(SPWeb web, string contentType, int userId)
        {
            List<LiteratureDto> literatureItems = new List<LiteratureDto>();
            var list = web.Lists[Lists.Pages];
            var queryString = @"<Where><And>
                                    <Eq><FieldRef Name='RealAuthor' LookupId='True' /><Value Type='User'>{0}</Value></Eq>
                                    <Eq><FieldRef Name='ContentType' /><Value Type='Text'>{1}</Value></Eq>
                                </And></Where>";
            queryString = string.Format(queryString, userId, contentType);

            var items = ExecuteQuery(list, queryString);
            literatureItems = ToLiteratureItems(web, items);
            return literatureItems;
        }

        public IList<LiteratureDto> GetUserLiteratureItems(string webUrl, string contentType, int userId, bool onlyApproved)
        {
            IList<LiteratureDto> literatureItems = new List<LiteratureDto>();

            var sec = new SPSecurity.CodeToRunElevated(delegate
            {
                using (var site = new SPSite(SiteId))
                using (var web = site.OpenWeb(webUrl))
                {
                    literatureItems = GetUserLiteratureItems(web,  contentType, userId, onlyApproved);
                }
            });
            SPSecurity.RunWithElevatedPrivileges(sec);

            return literatureItems;
        }

        private IList<LiteratureDto> GetUserLiteratureItems(SPWeb web, string contentType, int userId, bool onlyApproved)
        {
            var queryString = "<Where><And><Eq><FieldRef Name='RealAuthor' LookupId='True' /><Value Type='User'>{0}</Value></Eq>";
            queryString += "<Eq><FieldRef Name='ContentType' /><Value Type='Text'>{1}</Value></Eq></And></Where>";
            queryString += "<OrderBy><FieldRef Name='Created' Ascending='False'/></OrderBy>";
            queryString = string.Format(queryString, userId, contentType);

            var list = web.Lists["Lehed"];
            var items = ExecuteQuery(list, queryString);
            var result = ToLiteratureItems(web, items);

            if (result != null)
                if (onlyApproved)
                {
                    result = (from c in result
                              where c.Status == SPModerationStatusType.Approved
                              select c).ToList();
                }


            return result;
        }

        
        public void ApproveMagazine(int itemId, string webUrl, string comment, SPFieldLookupValueCollection keywords)
        {
            ModerateItem(true, itemId, webUrl, "Ajakirja kinnitamine", Emails.MagazineApprovedEmail, comment, keywords);
        }
        public void ApproveMagazine(int itemId, string webUrl, string comment)
        {
            ApproveMagazine(itemId, webUrl, comment, null);
        }

        public void DenieMagazine(int itemId, string webUrl, string comment)
        {
            ModerateItem(false, itemId, webUrl, "Ajakirja tagasilükkamine", Emails.MagazineRejectedEmail, comment, null);
        }

        public void ApproveBook(int itemId, string webUrl, string comment, SPFieldLookupValueCollection keywords)
        {
            ModerateItem(true, itemId, webUrl, "Raamatu kinnitamine", Emails.BookApprovedEmail, comment, keywords);
        }
        public void ApproveBook(int itemId, string webUrl, string comment)
        {
            ApproveBook(itemId, webUrl, comment, null);
        }

        public void DenieBook(int itemId, string webUrl,string comment)
        {
            ModerateItem(false, itemId, webUrl, "Raamatu tagasilükkamine", Emails.BookRejectedEmail, comment, null);
        }

        public void ModerateItem(bool approve, int itemId, string webUrl, string emailTitle, string email, string comment, SPFieldLookupValueCollection keywords)
        {
            var sec = new SPSecurity.CodeToRunElevated(delegate
            {
                using (var site = new SPSite(SiteId))
                using (var web = site.OpenWeb(webUrl))
                {
                    site.AllowUnsafeUpdates = true;
                    web.AllowUnsafeUpdates = true;

                    var list = web.Lists[Lists.Pages];
                    var item = list.GetItemById(itemId);
                    var literatureItem = new LiteratureDto(web, item);

                    if (item.ModerationInformation != null)
                    {
                        if (approve && (literatureItem.Status == SPModerationStatusType.Denied
                                            || literatureItem.Status == SPModerationStatusType.Pending))
                        {
                            if (keywords != null)
                            {
                                var tempFile = item.File;
                                if (tempFile.CheckOutStatus == SPFile.SPCheckOutStatus.None)
                                {
                                    tempFile.CheckOut();
                                }
                                item[Fields.EnetaKeywords.Name] = keywords;
                                item.SystemUpdate();

                                tempFile.CheckIn("Keywords changed");
                                item = tempFile.Item;
                            }

                            item.ModerationInformation.Status = SPModerationStatusType.Approved;
                        }
                        else if (!approve && (literatureItem.Status == SPModerationStatusType.Approved
                                                || literatureItem.Status == SPModerationStatusType.Pending))
                        {
                            item.ModerationInformation.Status = SPModerationStatusType.Denied;
                        }
                        item.ModerationInformation.Comment = comment;

                        item.Update();

                        //var body = "<html><body style='font-family:arial;font-size:10pt'><p>Hei " + literatureItem.Author + "!</p>";
                        //if (item.ModerationInformation.Status == SPModerationStatusType.Denied)
                        //    body += "<p>Sinu lisatud \"" + literatureItem.Title +"\" andmeid ei kinnitatud.</p>";
                        //else
                        //    if (item.ModerationInformation.Status == SPModerationStatusType.Approved)
                        //        body += "<p>Sinu lisatud \"" + literatureItem.Title + "\" andmed kinnitati.</p>";
                        //if (!string.IsNullOrEmpty(comment))
                        //    body += "<p>Administraatori selgitus: " + comment + "</p>";

                        //body += "<p>Tervitustega,<br/>";
                        //body += "Eneta tiim</p>";
                        //body += "<a href=\"http://www.eneta.ee\"><img src=\"http://www.eneta.ee/SiteCollectionImages/logod/eneta_logo_250x78_sinine.png\" border=\"0\"></a>";
                        //body += "</body></html>";
                        
                        //SPUtility.SendEmail(web, false, false, literatureItem.AuthorEmail, emailTitle, body);
                        //SPUtility.SendEmail(web, false, false, "abi@eneta.ee", emailTitle, body);

                        if (item.ModerationInformation.Status == SPModerationStatusType.Approved)
                        {
                            var mailer = new MailerService();
                            var addresses = new[] {literatureItem.AuthorEmail, "abi@eneta.ee"};
                            string itemType = "";
                            if (item.ContentType.Name == "Raamat")
                                itemType = "Book";
                            else
                                itemType = "Magazine";

                            mailer.SendMailByTemplate(itemType + "Accepted", literatureItem.Author, literatureItem.Title,
                                                      null, addresses);
                        }
                    }


                    site.AllowUnsafeUpdates = false;
                    web.AllowUnsafeUpdates = false;
                }
            });

            SPSecurity.RunWithElevatedPrivileges(sec);
        }

        public LiteratureDto GetRandomLiteratureItem(string webUrl, string contentType)
        {
            LiteratureDto result = null;

            var sec = new SPSecurity.CodeToRunElevated(delegate
            {
                using (var site = new SPSite(SiteId))
                using (var web = site.OpenWeb(webUrl))
                {
                    var list = web.Lists[Lists.Pages];
                    var queryString =
                                   "<Where><And><Eq><FieldRef Name='ContentType' /><Value Type='Text'>"+contentType+"</Value></Eq>" +
                                   "<Eq><FieldRef Name='_ModerationStatus' /><Value Type='ModStat'>Kinnitatud</Value></Eq></And></Where>";
                    var query = new SPQuery { Query = queryString };
                    var items = list.GetItems(query);

                    if (items == null)
                        return;
                    if (items.Count == 0)
                    {
                        Logger.LogInfo(
                            "OnLoad(): Found 0 items from literature list");
                        return;
                    }
                    var random = new Random(DateTime.Now.Millisecond);
                    var index = random.Next(0, items.Count - 1);
                    if (items.Count > 0)
                    {
                        result = new LiteratureDto(web, items[index]);
                    }
                }
            });
            SPSecurity.RunWithElevatedPrivileges(sec);

            return result;
        }

        #region Helpers
        
        private List<LiteratureDto>  ToLiteratureItems(SPWeb web, SPListItemCollection items)
        {
            List<LiteratureDto> result = new List<LiteratureDto>();
            if (items == null)
                return result;

            if (items.Count > 0)
            {
                foreach (SPListItem item  in items)
                {
                    var dto = new LiteratureDto(web, item);
                    result.Add(dto);
                }
            }
            Logger.LogInfo("ToLiteratureItems() added items: " + result.Count);
            return result;
        }



        private List<LiteratureDto> ToAdministratorList(SPListItemCollection items, SPUser author)
        {
            List<LiteratureDto> resultset = new List<LiteratureDto>();
            if (items == null)
                return resultset;
            if (items.Count == 0)
                return resultset;
            foreach (SPListItem item in items)
            {
                if (item.ModerationInformation == null)
                {
                    resultset.Add(new LiteratureDto(item.ParentList.ParentWeb, item));
                    continue;
                }
                
                if (item.ModerationInformation.Status != SPModerationStatusType.Denied)
                {
                    resultset.Add(new LiteratureDto(item.ParentList.ParentWeb, item));
                }
            }

            return resultset;
        }

        #endregion


        public void AddComment()
        {

        }

        public List<LiteratureCommentDto> GetLiteratureComments(string webUrl, string listName, string itemListInfo, int itemId)
        {
            List<LiteratureCommentDto> comments = new List<LiteratureCommentDto>();

            var sec = new SPSecurity.CodeToRunElevated(delegate
            {
                using (var site = new SPSite(SiteId))
                using (var web = site.OpenWeb(webUrl))
                {
                    SPList list = web.Lists[listName];
                    string queryString = @"<Where><And>
                                            <Eq><FieldRef Name='LiteratureCommentItemId'/><Value Type='Integer'>{0}</Value></Eq>
                                            <Eq><FieldRef Name='LiteratureCommentList'/><Value Type='Text'>{1}</Value></Eq>
                                           </And></Where>";

                    var items = base.ExecuteQuery(list, string.Format(queryString, itemId, itemListInfo));
                    if (items.Count > 0)
                    {
                        foreach (SPListItem item in items)
                        {
                            comments.Add(new LiteratureCommentDto(web, item));
                        }
                    }
                }
            });
            SPSecurity.RunWithElevatedPrivileges(sec);

            return comments;
        }

        public LiteratureDto GetBookBy(int id)
        {
            LiteratureDto dto = null;
            var sec = new SPSecurity.CodeToRunElevated(delegate
            {
               using (var site = new SPSite(SiteId))
               using (var web = site.OpenWeb("/oppimine/raamatud/"))
               {
                   dto = GetBookById(web, id);
               }
            });
            SPSecurity.RunWithElevatedPrivileges(sec);
            return dto;
        }

        private LiteratureDto GetBookById(SPWeb web, int id)
        {
            var list = web.Lists["Lehed"];
            var item = list.GetItemById(id);
            return CreateBookDto(item);
        }

        private LiteratureDto CreateBookDto(SPListItem item)
        {
            LiteratureDto dto = new LiteratureDto()
                                    {
                                        ID = item.ID,
                                        Title = item.Title,
 	                                };
            dto.LiteratureImageUrl = GetPictureUrl(item["FileLeafRef"].ToString(), item.ParentList.ParentWeb.Name);
            dto.LiteratureSmallImageUrl = GetSmallPictureUrl(item["FileLeafRef"].ToString(), item.ParentList.ParentWeb.Name);
            dto.Keywords = new List<KeywordDto>();
            var keywordsValues = item[Constants.Fields.EnetaKeywords.Name] as SPFieldLookupValueCollection;
            if (keywordsValues != null)
            {
                foreach (var keywordValue in keywordsValues)
                {
                    dto.Keywords.Add(new KeywordDto() { Id = keywordValue.LookupId, Title = keywordValue.LookupValue });
                }
            }

            if (item.ModerationInformation != null)
            {
                dto.Status = item.ModerationInformation.Status;
                dto.StatusComment = item.ModerationInformation.Comment;
            }
            var value = item["AdditionalInfoURL"];
            if (value != null)
            {
                var additionalInfoUrl = new SPFieldUrlValue(value.ToString());
                dto.AdditionalInfoURL = additionalInfoUrl.Url;
            }
            else
            {
                dto.AdditionalInfoURL = string.Empty;
            }
            var bookSummary = item[SPFields.PublishingPageContent] as string;
            if (!string.IsNullOrEmpty(bookSummary))
            {
                dto.Summary = bookSummary;
            }
            else
            {
                dto.Summary = string.Empty;
            }
            var userValue = item["RealAuthor"] as string;
            if (!string.IsNullOrEmpty(userValue))
            {
                var user = new SPFieldUserValue(item.ParentList.ParentWeb.Site.RootWeb, userValue);
                dto.AuthorId = user.User.ID;
                dto.Author = user.User.Name;
                dto.AuthorEmail = user.User.Email;

                var profileRepository = new UserProfileRepository(item.Web);
                var profile = profileRepository.GetUserProfileByProfileName(user.User.Name);
                if(profile != null)
                    dto.PosterProfileId = profile.Id;
            }
            var bookAuthors = item["Authors"];
            if (bookAuthors != null)
            {
                dto.BookAuthors = bookAuthors.ToString();
            }
            else
            {
                dto.BookAuthors = string.Empty;
            }
            var publishingYear = item["PublishYear"];
            if (publishingYear.IsSet())
            {
                dto.PublishingYear = publishingYear.ToString();
            } else
            {
                dto.PublishingYear = string.Empty;
            }
            var pageCount = item["PageCount"];
            if (pageCount.IsSet())
            {
                dto.PageCount = pageCount.ToString();
            } else
            {
                dto.PageCount = string.Empty;
            }
            var isbn10 = item["ISBN10"];
            if (isbn10.IsSet())
            {
                dto.Isbn10 = isbn10.ToString();
            }
            else
            {
                dto.Isbn10 = string.Empty;
            }
            var isbn13 = item["ISBN13"];
            if (isbn13.IsSet())
            {
                dto.Isbn13 = item["ISBN13"].ToString();
            } else
            {
                dto.Isbn13 = string.Empty;
            }
            dto.ItemUrl = SPUrlUtility.CombineUrl(item.ParentList.ParentWeb.ServerRelativeUrl, item.Url);
            dto.PostedDate = (DateTime)item[SPFields.Created];
            dto.LastModified = (DateTime)item[SPFields.Modified];
            return dto;
        }

        private string GetPictureUrl(string pageName, string webname)
        {
            var pictureName = pageName.Replace(".aspx", ".png");
            
            var pictureUrl = "/" + Lists.SiteCollectionImages + "/" + webname + "/" + pictureName;//Lists.Books.Images + pictureName;
            return pictureUrl;
        }

        private string GetSmallPictureUrl(string pageName, string webname)
        {
            var pictureName = pageName.Replace(".aspx", "_small.png");
            var pictureUrl = "/" + Lists.SiteCollectionImages + "/" + webname + "/" + pictureName;// Lists.Books.Images + pictureName;
            return pictureUrl;
        }

        public LiteratureDto GetLiteratureItemById(int id)
        {
            LiteratureDto item = null;
            var sec = new SPSecurity.CodeToRunElevated(delegate
            {
                using (var site = new SPSite(SiteId))
                using (var web = site.OpenWeb(WebId))
                {
                    item = GetLiteratureItem(web, id);
                }
            });
            SPSecurity.RunWithElevatedPrivileges(sec);

            return item;
        }

        private LiteratureDto GetLiteratureItem(SPWeb web, int id)
        {
            var list = web.Lists["Lehed"];
            var item = list.GetItemById(id);
            if (item.ContentType.Name == "Ajakiri")
                return CreateMagazineDto(item);
            else
                return CreateBookDto(item);
        }

        private LiteratureDto CreateMagazineDto(SPListItem item)
        {
            LiteratureDto dto = new LiteratureDto()
            {
                ID = item.ID,
                Title = item.Title,
            };
            dto.LiteratureImageUrl = GetPictureUrl(item["FileLeafRef"].ToString(), item.ParentList.ParentWeb.Name);
            dto.LiteratureSmallImageUrl = GetSmallPictureUrl(item["FileLeafRef"].ToString(), item.ParentList.ParentWeb.Name);
            dto.Keywords = new List<KeywordDto>();
            var keywordsValues = item[Constants.Fields.EnetaKeywords.Name] as SPFieldLookupValueCollection;
            if (keywordsValues != null)
            {
                foreach (var keywordValue in keywordsValues)
                {
                    dto.Keywords.Add(new KeywordDto() { Id = keywordValue.LookupId, Title = keywordValue.LookupValue });
                }
            }

            if (item.ModerationInformation != null)
            {
                dto.Status = item.ModerationInformation.Status;
                dto.StatusComment = item.ModerationInformation.Comment;
            }
            var value = item["AdditionalInfoURL"];
            if (value != null)
            {
                var additionalInfoUrl = new SPFieldUrlValue(value.ToString());
                dto.AdditionalInfoURL = additionalInfoUrl.Url;
            }
            else
            {
                dto.AdditionalInfoURL = string.Empty;
            }
            var bookSummary = item[SPFields.PublishingPageContent] as string;
            if (!string.IsNullOrEmpty(bookSummary))
            {
                dto.Summary = bookSummary;
            }
            else
            {
                dto.Summary = string.Empty;
            }
            var userValue = item["RealAuthor"] as string;
            if (!string.IsNullOrEmpty(userValue))
            {
                var user = new SPFieldUserValue(item.ParentList.ParentWeb.Site.RootWeb, userValue);
                dto.AuthorId = user.User.ID;
                dto.Author = user.User.Name;
                dto.AuthorEmail = user.User.Email;

                var profileRepository = new UserProfileRepository(item.Web);
                var profile = profileRepository.GetUserProfileByProfileName(user.User.Name);
                dto.PosterProfileId = profile.Id;
            }
            var bookAuthors = item["PublishingCountry"] as string;
            if (!string.IsNullOrEmpty(bookAuthors))
            {
                dto.BookAuthors = bookAuthors;
            }
            else
            {
                dto.BookAuthors = string.Empty;
            }
            var publishingYear = item["PublishingFrequency"];
            if (publishingYear.IsSet())
            {
                dto.PublishingYear = publishingYear.ToString();
            }
            else
            {
                dto.PublishingYear = string.Empty;
            }
            dto.ItemUrl = SPUrlUtility.CombineUrl(item.ParentList.ParentWeb.ServerRelativeUrl, item.Url);
            dto.PostedDate = (DateTime)item[SPFields.Created];
            dto.LastModified = (DateTime)item[SPFields.Modified];
            return dto;
        }



        public IList<LiteratureDto> GetPendingAndApprovedItems(string WebUrl, SPContentTypeId ctId, SPUser user)
        {
            //Todo: Add paging for performance

            List<LiteratureDto> books = new List<LiteratureDto>();

            var sec = new SPSecurity.CodeToRunElevated(delegate
            {
                using (SPSite site = new SPSite(SiteId))
                using (SPWeb studyWeb = site.OpenWeb(WebUrl))//webId))
                {
                    Logger.LogInfo("LiteratureRepository: " + studyWeb.Title);
                    var list = studyWeb.Lists[Lists.Pages];//studyWeb.GetList(listUrl);

                    var items = base.ExecuteQuery(list, "<Where><Eq><FieldRef Name='ContentTypeId'/><Value Type='Text'>"+ctId+"</Value></Eq></Where><OrderBy><FieldRef Name='Created' Ascending='False'/></OrderBy>");
                    Logger.LogInfo("LiteratureRepository: Leitud elemente: " + items.Count);
                    books = ToAdministratorList(items, user);
                }
            });
            SPSecurity.RunWithElevatedPrivileges(sec);
            return books;
        }

        public IList<LiteratureDto> GetUserAddedItems(string webUrl, SPContentTypeId ctId, SPUser user)
        {
            List<LiteratureDto> userAddedBooks = new List<LiteratureDto>();
            var sec = new SPSecurity.CodeToRunElevated(
                delegate
                {
                    using (SPSite site = new SPSite(SiteId))
                    using (SPWeb studyWeb = site.OpenWeb(webUrl))//webId))
                    {
                        Logger.LogInfo("LiteratureRepository: " + studyWeb.Title);
                        var list = studyWeb.Lists[Lists.Pages];//studyWeb.GetList(listUrl);

                        string queryString = string.Format(
                                                @"<Where>
                                                        <Eq><FieldRef Name='ContentTypeId'/><Value Type='Text'>{0}</Value></Eq>
                                                  </Where>
                                                  <OrderBy><FieldRef Name='Created' Ascending='False'/></OrderBy>", ctId);
                        var items = base.ExecuteQuery(list,queryString);
                        Logger.LogInfo("LiteratureRepository: Leitud elemente: " + items.Count);
                        userAddedBooks = ToList(items, user);
                    }
                });
            SPSecurity.RunWithElevatedPrivileges(sec);
            return userAddedBooks;
        }

        private List<LiteratureDto> ToList(SPListItemCollection items, SPUser user)
        {
            List<LiteratureDto> resultset = new List<LiteratureDto>();
            if (items == null)
                return resultset;
            if (items.Count == 0)
                return resultset;
            bool onlyApproved = false;
            if (user == null)
                onlyApproved = true;
            foreach (SPListItem item in items)
            {
                if (onlyApproved)
                {
                    if (item.ModerationInformation == null)
                        continue;
                    if (item.ModerationInformation.Status == SPModerationStatusType.Approved)
                    {
                        resultset.Add(new LiteratureDto(item.ParentList.ParentWeb, item));
                    }
                }
                else
                {
                    SPUser author;
                    if (item.ModerationInformation == null)
                    {
                        if (IsAuthor(item, user))
                        {
                            resultset.Add(new LiteratureDto(item.ParentList.ParentWeb, item));
                            continue;
                        }
                    }
                    else if (item.ModerationInformation.Status != SPModerationStatusType.Approved && IsAuthor(item, user))
                    {
                        resultset.Add(new LiteratureDto(item.ParentList.ParentWeb, item));
                    }
                    else if (item.ModerationInformation.Status == SPModerationStatusType.Approved)
                    {
                        resultset.Add(new LiteratureDto(item.ParentList.ParentWeb, item));
                    }
                    else
                    {
                        Logger.LogInfo(string.Format("Üksus: {0}, on staatusega {1} ja ei ole nähtav", item.Title, item.ModerationInformation.Status));
                    }
                }
            }

            return resultset;
        }

        private bool IsModerated(SPListItem item)
        {
            return (item.ModerationInformation == null);
        }

        private bool GetAuthor(SPWeb web, object authorFieldValue, out SPUser user) 
        {
            if (authorFieldValue == null)
            {
                user = null;
                return false;
            }
            var authorValue = new SPFieldUserValue(web, authorFieldValue.ToString());
            if (authorValue != null)
            {
                user = authorValue.User;
                return true;
            }
            user = null;
            return false;
        }

        private bool IsAuthor(SPListItem item, SPUser currentUser)
        {
            if (item == null)
                return false;
            SPUser user;
            if (GetAuthor(item.ParentList.ParentWeb, item["RealAuthor"], out user))
            {
                if (currentUser == null)
                    return false;
                if (currentUser.LoginName.Equals(user.LoginName))
                    return true;
                else
                    return false;
            }
            else
            {
                return false;
            }
        }
    }
}
